package com.um.springboot.starter.service.impl;

import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.http.HttpUtil;
import com.um.springboot.starter.constants.SmsConsts;
import com.um.springboot.starter.properties.YtxSmsProperties;
import com.um.springboot.starter.service.SmsService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.LinkedHashMap;

/**
 * 易通讯短信服务
 * https://accessyou.com/index.php
 */
@Slf4j
@Component(SmsConsts.YTX_IMPL)
public class YtxSmsServiceImpl implements SmsService {

    @Autowired
    YtxSmsProperties ytxSmsProperties;

    /**
     * 发送短信
     *
     * @param mobileAreaCode 国家代码
     * @param mobile         手机号
     * @param template       模板
     * @param params         模板参数
     * @param customSmsProps 自定义配置
     * @return 是否成功
     */
    @Override
    public boolean send(String mobileAreaCode, String mobile, String template, LinkedHashMap<String, String> params, Object customSmsProps) {
        YtxSmsProperties props = ObjectUtil.defaultIfNull((YtxSmsProperties) customSmsProps, ytxSmsProperties);

        String phone = mobileAreaCode + mobile;
        String message = StrUtil.format(props.getTemplates().get(template), params.values());
        String body = HttpUtil.createGet("https://basic.accessyou-api.com/sms/sendsms-utf8-senderid.php")
                .form("accountno", props.getAccountNo())
                .form("pwd", props.getPwd())
                .form("from", props.getFrom())
                .form("size", "l")
                .form("phone", phone)
                .form("msg", message)
                .setConnectionTimeout(300000)
                .timeout(300000)
                .setReadTimeout(300000)
                .execute()
                .body();
        log.info("【易通讯短信发送】 \n电话：{} \n短信内容：{} \n发送结果：{}", phone, message, body);
        return true;
    }

}
